﻿using System;
using System.Text;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.UI.WebControls;

namespace Salient.Web.Administration.Security.Permissions
{
    public partial class createPermission : SecurityPage
    {
        public void AddPermissionRule(string currentPath, TextBox userName, ListControl roles, CheckBox userRadio,
                                      CheckBox roleRadio, CheckBox allUsersRadio, CheckBox anonymousUsersRadio,
                                      CheckBox grantRadio, CheckBox denyRadio)
        {
            System.Configuration.Configuration config = OpenWebConfiguration(currentPath, true);
            var auth = (AuthorizationSection) config.GetSection("system.web/authorization");

            var rule =
                new AuthorizationRule(grantRadio.Checked ? AuthorizationRuleAction.Allow : AuthorizationRuleAction.Deny);

            if (userRadio.Checked)
            {
                rule.Users.Add(userName.Text);
            }
            else if (roleRadio.Checked)
            {
                rule.Roles.Add(roles.SelectedItem.Text);
            }
            else if (allUsersRadio.Checked)
            {
                rule.Users.Add("*");
            }
            else if (anonymousUsersRadio.Checked)
            {
                rule.Users.Add("?");
            }

            auth.Rules.Add(rule);
            SaveConfig(config);
        }

        private string GetDirectory(string path)
        {
            if (path == null)
            {
                return null;
            }

            if (path.LastIndexOf('/') == -1)
            {
                return "/";
            }

            return path.Substring(path.LastIndexOf('/') + 1);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!IsPostBack)
            {
                // Note: treenodes persist when added in Init, before loadViewState
                var n = new TreeNode(GetDirectory(ApplicationPath), ApplicationPath);
                tv.Nodes.Add(n);
                n.Selected = true;
                if (String.IsNullOrEmpty(CurrentPath))
                {
                    CurrentPath = ApplicationPath;
                }
                PopulateChildren(n, CurrentPath);
            }
        }

        public void Page_Init()
        {
            if (IsWindowsAuth())
            {
                findUsersLink.Visible = false;
            }
        }

        public void Page_Load()
        {
            if (!IsPostBack)
            {
                if (IsRoleManagerEnabled())
                {
                    roles.DataSource = (string[]) CallWebAdminHelperMethod(false, "GetAllRoles", new object[] {}, null);
                    roles.DataBind();
                    if (roles.Items.Count == 0)
                    {
                        var item = new ListItem((string) GetLocalResourceObject("NoRoles"));
                        roles.Items.Add(item);
                        roles.Enabled = false;
                        roleRadio.Enabled = false;
                        roleRadio.Checked = false;
                        userRadio.Checked = true;
                    }
                }
                else
                {
                    var item = new ListItem((string) GetLocalResourceObject("RolesDisabled"));
                    roles.Items.Add(item);
                    roles.Enabled = false;
                    roleRadio.Enabled = false;
                    roleRadio.Checked = false;
                    userRadio.Checked = true;
                }

                var builder = new StringBuilder();
                bool firstTime = true;
                foreach (string mu in UserCollection.Keys)
                {
                    if (!firstTime)
                    {
                        builder.Append(",");
                    }
                    else
                    {
                        firstTime = false;
                    }
                    builder.Append(mu);
                }
                userName.Text = builder.ToString();
            }
            HighlightSelectedNode(tv.Nodes[0], CurrentPath);
        }

        public bool HighlightSelectedNode(TreeNode node, string path)
        {
            bool foundIt = false;
            foreach (TreeNode childNode in node.ChildNodes)
            {
                if (childNode.Value == path)
                {
                    childNode.Selected = true;
                    foundIt = true;
                    break;
                }
            }
            return foundIt;
        }

        private void PopulateChildren(TreeNode parent, string selectNodeValue)
        {
            if (parent.ChildNodes.Count == 0)
            {
                VirtualDirectory vdir = GetVirtualDirectory(parent.Value);
                foreach (VirtualDirectory childVdir in vdir.Directories)
                {
                    string childValue = parent.Value + "/" + childVdir.Name;
                    var newNode = new TreeNode(childVdir.Name, childValue);
                    if (selectNodeValue != null && childValue == selectNodeValue)
                    {
                        //newNode.Selected = true;
                        newNode.SelectAction = TreeNodeSelectAction.Select;
                    }
                    parent.ChildNodes.Add(newNode);
                }
            }
        }

        protected void TreeNodeExpanded(Object sender, TreeNodeEventArgs e)
        {
            foreach (TreeNode child in e.Node.ChildNodes)
            {
                PopulateChildren(child, CurrentPath);
            }
        }

        protected void TreeNodeSelected(object sender, EventArgs e)
        {
            CurrentPath = ((TreeView) sender).SelectedNode.Value;
        }

        protected void UpdateAndReturnToPreviousPage(object sender, EventArgs e)
        {
            ClearUserCollection();
            if (!IsRuleValid(placeholderValidator, userRadio, userName, roleRadio, roles))
            {
                return;
            }
            AddPermissionRule(CurrentPath, userName, roles, userRadio, roleRadio, allUsersRadio, anonymousUsersRadio,
                              grantRadio, denyRadio);
            ReturnToPreviousPage(sender, e);
        }
    }
}